import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // 设置网页动态标题
  document.title = getPageTitle(to.meta.title)
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      // 有token，还去登录 ---> 直接去主页
      next('/')
      NProgress.done()
    } else {
      // 1. 获取个人信息
      // if (没有userId) {
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log(menus, 'menu')
        console.log(asyncRoutes, 'asyncRoutes')
        const filterRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        console.log(filterRoutes, 'filterRoutes')
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenuList', filterRoutes)
        // 白屏的问题是因为页面刷新的时候，会重新执行addRoutes,而addRoutes没有执行完成
        // 直接使用next()放行会出现白屏问题 需要设置{...to,replace:true} 保证addRoutes执行完成
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    // 没有token，只能访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
